<?php

namespace app\admin\controller;

use think\Controller;

class Login extends Controller
{
    public function index()
    {
        if (\request()->isPost()) {
            $data = input('post.');
            if (!captcha_check($data['captcha'])) {
                $this->error('验证码错误');
            }
            $user = model('manager')->get(['mg_name' => $data['mg_name']]);
            if (!$user) {
                $this->error('该用户不存在或未验证通过');
            }
            //密码验证
            if (MD5($data['password'] . $user['code']) != $user['password']) {
                $this->error('密码不正确');
            }
            //将用户信息保存到session中
            session('manager', $user, 'admin');
            //登录成功
            $this->success('登录成功', url('index/index'));
        } else {
            //获取session值
            $account = session('manager', '', 'admin');
            if ($account && $account->id) {
                $this->redirect(url('index/index'));
            }
            return $this->fetch();
        }
    }

    //退出登录
    public function logout()
    {
        session(null, 'admin');
        return $this->redirect(url('login/index'));
    }
}